﻿<template>
    <div class="CheckWireropeDetail">
        <MyDialog :model-value="true" :type="DialogType.C2" :title="title" @close="onClose">
            <el-tabs v-model="activeName" type="border-card">
                <el-tab-pane label="基本信息" name="基本信息">
                    <el-form ref="CheckWireropeDetailFormRef" label-width="110" :model="thisData" :rules="rules">
                        <div class="rowTitle">检测信息</div>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="检测类型" prop="type">
                                    <EnumSelect class="w-100" :enums="Enums.Check_Type" v-model:id="thisData.type" :disabled="isSee"></EnumSelect>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="检测单位" prop="checkUnit">
                                    <el-input v-model="thisData.checkUnit" maxlength="50" :disabled="isSee"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="检测人员" prop="checkUserName">
                                    <el-input v-model="thisData.checkUserName" maxlength="50" :disabled="isSee"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="检测日期" prop="checkDate">
                                    <el-date-picker class="w-100" v-model="thisData.checkDate" :disabled-date="checkDateDisabledDate" type="date" :disabled="isSee" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="下次检测日期" prop="nextCheckDate" :required="!!(thisData.type == Enums.Check_Type.定期)">
                                    <el-date-picker class="w-100" v-model="thisData.nextCheckDate" :disabled="isSee" type="date" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="是否建议更换">
                                    <el-radio-group v-model="thisData.isSuggestChange" class="ml-4" :disabled="isSee">
                                        <el-radio :label="false" size="default">否</el-radio>
                                        <el-radio :label="true" size="default">是</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <div class="rowTitle">钢丝绳信息</div>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="钢丝绳编码" prop="usingWireropeID">
                                    <el-input v-model="usingWireropeData.code" disabled maxlength="50">
                                        <template #append v-if="!isSee">
                                            <el-button @click="onOpenUsingWireropeSelect">
                                                <el-icon>
                                                    <Search />
                                                </el-icon>
                                            </el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="在用绳名称" prop="name">
                                    <el-input v-model="usingWireropeData.name" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="规格型号" prop="guiGe">
                                    <el-input v-model="usingWireropeData.guiGe" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="直径" prop="diameter">
                                    <el-input v-model="usingWireropeData.diameter" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="制造单位" prop="producerName">
                                    <el-input v-model="usingWireropeData.producerName" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="使用单位" prop="department_Name">
                                    <el-input v-model="usingWireropeData.department_Name" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="提升机用途" prop="hoisterUsageName">
                                    <el-input v-model="usingWireropeData.hoisterUsageName" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="钢丝绳类型" prop="wireropeTypeName">
                                    <el-input v-model="usingWireropeData.wireropeTypeName" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="安装日期" prop="installDate">
                                    <el-date-picker class="w-100" v-model="usingWireropeData.installDate" type="date" :disabled="true" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="安装长度" prop="installLengthNum">
                                    <el-input v-model="usingWireropeData.installLengthNum" maxlength="50" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="安全运行时长" prop="dayNum">
                                    <el-input v-model="usingWireropeData.dayNum" maxlength="50" :disabled="true">
                                        <template #append>天</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="上次维保日期" prop="doDate">
                                    <el-date-picker class="w-100" v-model="usingWireropeData.lastUsingWireropeKeepModel.doDate" type="date" :disabled="true" v-if="usingWireropeData.lastUsingWireropeKeepModel" />
                                    <el-date-picker class="w-100" type="date" :disabled="true" v-else />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="上次检测日期" prop="lastCheckWireropeModel.checkDate">
                                    <el-date-picker class="w-100" v-model="usingWireropeData.lastCheckWireropeModel.checkDate" type="date" :disabled="true" v-if="usingWireropeData.lastCheckWireropeModel" />
                                    <el-date-picker class="w-100" type="date" :disabled="true" v-else />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
                <template v-for="(item, index) in checkWireropeDetailModels">
                    <el-tab-pane :label="index + 1 + '号绳'" :name="index + 1">
                        <el-form ref="checkWireropeFormRef" label-width="130" :model="item" :rules="wirerRules">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="绳名称" prop="name">
                                        <el-input v-model="item.name" :disabled="!isFirst" maxlength="50"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="附件">
                                        <ButtonImage v-model="item.attr_FilesList" appendToBody :readonly="isSee" type="primary" :text="isSee ? '查看' : '上传'"></ButtonImage>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <div class="titWarp">
                                <div class="rowTitle">断丝</div>
                                <el-button type="primary" @click="onShowDataEntry(item, Enums.DataEntry_Type.断丝, index)">{{ isSee ? "查看" : "录入" }}数据</el-button>
                            </div>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="捻距内断丝数" prop="dsCnt">
                                        <el-input v-model="item.dsCnt" :disabled="isSee" maxlength="50" @change="change_dsCnt(item, index)"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="位置">
                                        <el-button type="primary" @click="onShowLookPosition(item, index)">
                                            {{ isSee ? "查看" : "编辑" }}
                                            <el-icon class="el-icon--right" v-if="item.checkWireropeDetailPositionModels && item.checkWireropeDetailPositionModels.length">
                                                <Select />
                                            </el-icon>
                                        </el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="捻距内新增断丝数">
                                        <el-input v-model="item.dsCntAdd" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="新增断丝总数">
                                        <el-input v-model="item.allCntAdd" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="LA" prop="dsLa">
                                        <div class="infoBox">
                                            <InputNumber v-model="item.dsLa" :precision="2" append="%" maxlength="50" :disabled="isSee"></InputNumber>
                                            <el-tooltip :content="usingWireropeData.laRemark" placement="top">
                                                <el-icon v-if="usingWireropeData.laRemark"><QuestionFilled /></el-icon>
                                            </el-tooltip>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <div class="titWarp">
                                <div class="rowTitle">直径</div>
                                <el-button type="primary" @click="onShowDataEntry(item, Enums.DataEntry_Type.直径, index)">{{ isSee ? "查看" : "录入" }}数据</el-button>
                            </div>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="位置" prop="zjPosition">
                                        <InputNumber v-model="item.zjPosition" :precision="2" append="m" maxlength="50" :disabled="isSee"></InputNumber>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="DIA" prop="zjDia">
                                        <div class="infoBox">
                                            <InputNumber v-model="item.zjDia" :precision="2" append="%" maxlength="50" :disabled="isSee"></InputNumber>
                                            <el-tooltip :content="usingWireropeData.diaRemark" placement="top">
                                                <el-icon v-if="usingWireropeData.diaRemark"><QuestionFilled /></el-icon>
                                            </el-tooltip>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <div class="titWarp">
                                <div class="rowTitle">金属截面损失</div>
                            </div>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="位置" prop="jsjmPosition">
                                        <InputNumber v-model="item.jsjmPosition" :precision="2" append="m" maxlength="50" :disabled="isSee"></InputNumber>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="LMA" prop="jsjmLma">
                                        <div class="infoBox">
                                            <InputNumber v-model="item.jsjmLma" :precision="2" append="%" maxlength="50" :disabled="isSee"></InputNumber>
                                            <el-tooltip :content="usingWireropeData.lmaRemark" placement="top">
                                                <el-icon v-if="usingWireropeData.lmaRemark"><QuestionFilled /></el-icon>
                                            </el-tooltip>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <div class="titWarp">
                                <div class="rowTitle">捻距变化</div>
                            </div>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="捻距" prop="nianJu">
                                        <InputNumber v-model="item.nianJu" :precision="2" append="mm" maxlength="50" :disabled="isSee" @change="onNianJuChange($event, index)"></InputNumber>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="LL" prop="nianJuChange">
                                        <div class="infoBox">
                                            <InputNumber v-model="item.nianJuChange" :precision="2" append="%" maxlength="50" :disabled="true"></InputNumber>
                                            <el-tooltip :content="usingWireropeData.nianJuRemark" placement="top">
                                                <el-icon v-if="usingWireropeData.nianJuRemark"><QuestionFilled /></el-icon>
                                            </el-tooltip>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <div class="titWarp">
                                <div class="rowTitle">其他</div>
                            </div>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="腐蚀情况" prop="othFuShi">
                                        <el-input v-model="item.othFuShi" :disabled="isSee" maxlength="50"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="磨损情况" prop="othMoSun">
                                        <el-input v-model="item.othMoSun" :disabled="isSee" maxlength="50"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="其他损伤" prop="othQiTa">
                                        <el-input v-model="item.othQiTa" :disabled="isSee" maxlength="50"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="综合判定" prop="othZongHe">
                                        <el-input v-model="item.othZongHe" :disabled="isSee" maxlength="50"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </el-tab-pane>
                </template>
            </el-tabs>

            <template #footer>
                <el-button type="warning" :loading="loading" @click="onDownloadExcel" v-if="!isSee" style="position: absolute; left: 10px">下载模板</el-button>
                <el-button type="primary" :loading="loading" @click="onUploadExcel" v-if="!isSee" style="position: absolute; left: 98px">导入</el-button>
                <el-button type="primary" :loading="loading" @click="onSubmit" v-if="!isSee">提交</el-button>
            </template>
        </MyDialog>

        <UsingWireropeSelect v-if="isShowUsingWireropeSelect" :hasCheckbox="false" :hasRadio="true" @close="onCloseUsingWireropeSelect"></UsingWireropeSelect>

        <!-- 数据录入 -->
        <DataEntry ref="DataEntryRef" v-if="isShowDataEntry" @close="onCloseDataEntry" :isChange="!isSee"></DataEntry>

        <!-- 位置信息 -->
        <LookPosition ref="LookPositionRef" v-if="isShowLookPosition" @close="onClosePosition" :isChange="!isSee"></LookPosition>

        <input class="dispn" ref="fileRef" type="file" @change="onChangeExcel" />
    </div>
</template>

<script lang="ts" setup>
import _, { find } from "lodash";
import Enums from "@/gx/Enums";
import Gx from "@/gx/Gx";
import { FormRules } from "element-plus";
import { DatePart, DialogType, TipsType } from "@/_gx/TsEnums";
import UsingWireropeSelect from "@/views/wi/UsingWirerope/UsingWireropeSelect.vue";
import DataEntry from "./DataEntry.vue";
import LookPosition from "./LookPosition.vue";
import LAY_EXCEL from "lay-excel";

//接收父组件的传值
const rowAutoID = inject("rowAutoID") as Ref<number | null>;

//查看
const isSee = ref(false);
// 检测
const isEdit = ref(false);
// 是否是第一次检测
const isFirst = ref(false);

//loading...
const loading = ref(false);

//定义当前页面数据对象
const thisData = ref<any>({
    type: Enums.Check_Type.日常,
    isSuggestChange: false,
});

//定义表单验证规则
const rules = ref<FormRules>({
    type: [{ required: true, message: "请选择检测类型", trigger: "blur" }],
    checkUnit: [{ required: true, message: "请输入检测单位", trigger: "blur" }],
    checkUserName: [{ required: true, message: "请输入检测人员", trigger: "blur" }],
    checkDate: [{ required: true, message: "请选择检测日期", trigger: "blur" }],
    usingWireropeID: [{ required: true, message: "请选择钢丝绳", trigger: ["blur", "change"] }],
    nextCheckDate: [
        {
            validator: (rule, value, callback) => {
                if (Gx.IsEmpty(value) && thisData.value.type == Enums.Check_Type.定期) {
                    callback(new Error("请选择下次检测日期"));
                } else {
                    callback();
                }
            },
            trigger: ["blur", "change"],
        },
    ],
});
const wirerRules = ref<FormRules>({
    name: [{ required: true, message: "请输入绳名称", trigger: "blur" }],
    dsCnt: [{ required: true, message: "请输入捻距内断丝数", trigger: "blur" }],
    dsLa: [{ required: true, message: "请输入断丝LA", trigger: "blur" }],
    zjPosition: [{ required: true, message: "请输入直径位置", trigger: "blur" }],
    zjDia: [{ required: true, message: "请输入直径DIA", trigger: "blur" }],
    jsjmPosition: [{ required: true, message: "请输入金属截面损失位置", trigger: "blur" }],
    jsjmLma: [{ required: true, message: "请输入金属截面损失LMA", trigger: "blur" }],
    othFuShi: [{ required: true, message: "请输入腐蚀情况", trigger: "blur" }],
    othMoSun: [{ required: true, message: "请输入磨损情况", trigger: "blur" }],
    othQiTa: [{ required: true, message: "请输入其他损伤", trigger: "blur" }],
    othZongHe: [{ required: true, message: "请输入综合判定", trigger: "blur" }],
});

//标题
const title = computed(() => {
    if (Gx.IsEmpty(rowAutoID.value)) {
        return "在用绳检测详情 - 创建";
    } else {
        return `在用绳检测详情 - 编辑 - ${usingWireropeData.value.name}`;
    }
});

//检测日期限制
const checkDateDisabledDate = (time) => {
    if (time.getTime() > Date.now()) {
        return true;
    } else {
        return false;
    }
};

const activeName = ref("基本信息");

const usingWireropeData = ref<any>({});
const checkWireropeDetailModels = ref([]);

const prevCheckData = ref<any>({});
let oldCheckWireropeDetailModels = [];

//向子组件传值
const usingWireropeID = ref<number | null>(null);
provide("usingWireropeID", usingWireropeID);
const installLengthNum = ref<number | null>(null);
provide("installLengthNum", installLengthNum);

//初始化
const Init = async (type, wireID) => {
    usingWireropeID.value = wireID;
    if (type == "查看") {
        isSee.value = true;
    }
    if (type == "检测") {
        isEdit.value = true;
    }
    if (!Gx.IsEmpty(rowAutoID.value)) {
        await App.CallApi(Api.CheckWirerope.GetByID(rowAutoID.value), {
            success: (res) => {
                thisData.value = res;
                //循环绳子过滤类型
                for (var i = 0; i < res.checkWireropeDetailModels.length; i++) {
                    let item = res.checkWireropeDetailModels[i];
                    item.dsList = item.checkWireropeDetailDataModels.filter((x) => x.type == Enums.DataEntry_Type.断丝);
                    item.zjList = item.checkWireropeDetailDataModels.filter((x) => x.type == Enums.DataEntry_Type.直径);
                }
                checkWireropeDetailModels.value = res.checkWireropeDetailModels;
            },
        });
        //获取绳子相关信息
        await App.CallApi(Api.UsingWirerope.GetStatusMonitorByID(wireID), {
            success: (res) => {
                //有检测记录
                if (res.lastCheckWireropeModel && res.lastCheckWireropeModel.checkWireropeDetailModels && res.lastCheckWireropeModel.checkWireropeDetailModels.length) {
                    isFirst.value = false;
                    for (var i = 0; i < checkWireropeDetailModels.value.length; i++) {
                        let item = checkWireropeDetailModels.value[i];
                        //从上次监测记录中拿到绳名称
                        var findItem = res.lastCheckWireropeModel.checkWireropeDetailModels.find((x) => {
                            return x.sortNo === item.sortNo;
                        });

                        item.name = findItem.name;
                    }
                } else {
                    isFirst.value = true;
                }
                //计算安全运行时长
                let dayNum = Gx.DateDiff(DatePart.Day, res.installDate, Gx.GetDateTime());
                res.dayNum = dayNum;

                usingWireropeData.value = res;
                installLengthNum.value = res.installLengthNum;
            },
        });

        oldCheckWireropeDetailModels = Gx.DeepCopy(checkWireropeDetailModels.value);

        getPrevRecord(thisData.value.usingWireropeID);
    }
};

//表单Ref对象
const CheckWireropeDetailFormRef = ref(null);

// 捻距数据变化
const onNianJuChange = (val, index) => {
    if (isSee.value) {
        return;
    }
    let nianJu = usingWireropeData.value.nianJu;
    let nianJuChange = Math.abs(Gx.Chu(Gx.Jian(val, nianJu), nianJu) * 100).toFixed(2);

    checkWireropeDetailModels.value[index].nianJuChange = nianJuChange;
};

//提交
const onSubmit = () => {
    for (let i = 0; i < checkWireropeDetailModels.value.length; i++) {
        let obj = checkWireropeDetailModels.value[i];
        let sortNo = Number(i) + 1;
        obj.checkWireropeDetailDataModels = [...obj.dsList, ...obj.zjList];
        obj.usingWireropeID = thisData.value.usingWireropeID;
        obj.sortNo = sortNo;
        for (let item in obj) {
            if (Gx.IsEmpty(obj[item]) && item != "attr_Files") {
                App.Tips({ msg: "请完善" + (Number(i) + 1) + "号绳信息！" });
                return;
            }
        }
    }

    CheckWireropeDetailFormRef.value.validate((isOk: boolean) => {
        if (!isOk) {
            return;
        }

        let _api = null;
        let _data = thisData.value;

        _data.checkWireropeDetailModels = checkWireropeDetailModels.value;
        _data.status = Enums.CheckWirerope_Status.已检测;
        if (Gx.IsEmpty(rowAutoID.value)) {
            //添加
            _api = Api.CheckWirerope.Insert;
        } else {
            //检测
            _api = Api.CheckWirerope.Check;
            if (Gx.IsEmpty(thisData.value.nextCheckDate)) {
                App.Tips({ msg: "请选择基本信息下次监测日期！" });
                return;
            }
        }
        loading.value = true;
        App.CallApi(_api, {
            data: _data,
            success: (res) => {
                emits("close", true);
            },
            complete: () => {
                loading.value = false;
            },
        });
    });
};

/********************************************** 钢丝绳选择 **********************************************/
let isShowUsingWireropeSelect = ref(false);

//打开钢丝绳选择
const onOpenUsingWireropeSelect = () => {
    if (!isSee.value && !isEdit.value) {
        isShowUsingWireropeSelect.value = true;
    }
};

//默认绳信息参数
let wireropeObj = {
    dsList: [],
    zjList: [],
    attr_FilesList: [],
    checkWireropeDetailDataModels: [],
    checkWireropeDetailPositionModels: [],
    dsCnt: null,
    dsLa: null,
    zjDia: null,
    zjPosition: null,
    jsjmLma: null,
    jsjmPosition: null,
    nianJu: null,
    nianJuChange: null,
    othFuShi: null,
    othMoSun: null,
    othQiTa: null,
    othZongHe: null,
};
//关闭钢丝绳选择
const onCloseUsingWireropeSelect = (selectData) => {
    isShowUsingWireropeSelect.value = false;

    if (!Gx.IsEmpty(selectData)) {
        thisData.value.usingWireropeID = selectData.usingWireropeID;
        usingWireropeID.value = selectData?.usingWireropeID;
        installLengthNum.value = selectData.installLengthNum;

        //查询绳子检测信息
        App.CallApi(Api.UsingWirerope.GetStatusMonitorByID(selectData.usingWireropeID), {
            success: (res) => {
                //计算安全运行时长
                let dayNum = Gx.DateDiff(DatePart.Day, res.installDate, Gx.GetDateTime());
                res.dayNum = dayNum;

                usingWireropeData.value = res;
                checkWireropeDetailModels.value = [];
                // 是否有过检测
                if (res.lastCheckWireropeModel && res.lastCheckWireropeModel.checkWireropeDetailModels) {
                    isFirst.value = false;
                    //循环绳子过滤类型
                    for (var i = 0; i < res.lastCheckWireropeModel.checkWireropeDetailModels.length; i++) {
                        let item = res.lastCheckWireropeModel.checkWireropeDetailModels[i];
                        checkWireropeDetailModels.value.push({ name: item.name, ...wireropeObj });
                    }
                } else {
                    isFirst.value = true;
                    for (var i = 0; i < res.cnt; i++) {
                        checkWireropeDetailModels.value.push({ name: "", ...wireropeObj });
                    }
                }

                oldCheckWireropeDetailModels = Gx.DeepCopy(checkWireropeDetailModels.value);
            },
        });
        getPrevRecord(thisData.value.usingWireropeID);
    }
};

/********************************************** 数据录入 **********************************************/
//是否显示详情对话框
const isShowDataEntry = ref(false);
const isShowLookPosition = ref(false);
//详情对话框Ref对象
const DataEntryRef = ref(null);
const LookPositionRef = ref(null);
//显示详情
const onShowDataEntry = (data, type, index) => {
    isShowDataEntry.value = true;
    nextTick(() => {
        DataEntryRef.value.InitDataEntry(data.name, type == Enums.DataEntry_Type.断丝 ? data.dsList : data.zjList, type, usingWireropeData.value, index);
    });
};
const onShowLookPosition = (data, index) => {
    isShowLookPosition.value = true;
    nextTick(() => {
        LookPositionRef.value.InitLookPosition(data.name, data.checkWireropeDetailPositionModels, index);
    });
};

//关闭详情
const onCloseDataEntry = (list, position, maxSum, type, wireIndex) => {
    isShowDataEntry.value = false;
    if (list) {
        if (type == Enums.DataEntry_Type.断丝) {
            checkWireropeDetailModels.value[wireIndex].dsCnt = maxSum;
            checkWireropeDetailModels.value[wireIndex].checkWireropeDetailPositionModels = position;
            checkWireropeDetailModels.value[wireIndex].dsList = list;
            change_dsCnt(checkWireropeDetailModels.value[wireIndex], wireIndex);
            change_allCntAdd(checkWireropeDetailModels.value[wireIndex], wireIndex);
        } else if (type == Enums.DataEntry_Type.直径) {
            checkWireropeDetailModels.value[wireIndex].zjPosition = position;
            checkWireropeDetailModels.value[wireIndex].zjDia = maxSum;
            checkWireropeDetailModels.value[wireIndex].zjList = list;
        }
    }
};
const onClosePosition = (list, wireIndex) => {
    isShowLookPosition.value = false;
    if (list) {
        checkWireropeDetailModels.value[wireIndex].checkWireropeDetailPositionModels = list;
    }
};

//关闭
const onClose = () => {
    emits("close", false);
};

//向上抛出的事件与方法
const emits = defineEmits(["close"]);
defineExpose({ Init });

/********************************************** 其它方法定义 **********************************************/
//获取上一次检测记录，用以自动计算捻距内新增断丝数和本次新增总断丝数
const getPrevRecord = (id) => {
    App.CallApi(Api.CheckWirerope.GetPrevCheckWireropeModel, {
        data: {
            _UsingWireropeID: id,
            _CreateDate: thisData.value.createDate,
        },
        success: (res) => {
            prevCheckData.value = res;
        },
    });
};

//
const change_dsCnt = (item, index) => {
    let prev_val = 0;
    let prev_item = _.find(prevCheckData.value.checkWireropeDetailModels, function (obj) {
        return obj.name == item.name;
    });
    if (prev_item != undefined) {
        prev_val = prev_item.dsCnt;
    }
    let temp = checkWireropeDetailModels.value[index];
    temp.dsCntAdd = parseInt(item.dsCnt) - prev_val;
    checkWireropeDetailModels.value[index] = temp;
};

const change_allCntAdd = (item, index) => {
    let prev_val = 0;
    let prev_item = _.find(prevCheckData.value.checkWireropeDetailModels, function (obj) {
        return obj.name == item.name;
    });
    if (prev_item != undefined) {
        prev_val = _.sumBy(prev_item.checkWireropeDetailDataModels, function (obj: any) {
            if (obj.type == Enums.DataEntry_Type.断丝) {
                return obj.num;
            } else {
                return 0;
            }
        });
    }
    let temp = checkWireropeDetailModels.value[index];
    let cur_sum = _.sumBy(temp.dsList, function (obj: any) {
        return obj.num;
    });

    temp.allCntAdd = cur_sum - prev_val;
    checkWireropeDetailModels.value[index] = temp;
};

/********************************************** 下载模板、导入 **********************************************/

//下载模板
const onDownloadExcel = () => {
    window.open("/Upload/在用绳检测结果导入模板.xlsx");
};

const fileRef = ref(null);

//导入
const onUploadExcel = () => {
    if (Gx.IsEmpty(usingWireropeID.value)) {
        App.Tips({ msg: "请选择钢丝绳编码!" });
        return;
    }

    fileRef.value.click();
};

//触发文件选择框改变事件，并上传
const onChangeExcel = () => {
    LAY_EXCEL.importExcel(fileRef.value.files, {}, (data) => {
        fileRef.value.value = "";
        readExcel(data);
    });
};

const readExcel = (data) => {
    if (Gx.IsEmpty(data) || data.length == 0 || Gx.IsEmpty(data[0]["Sheet1"])) {
        App.Tips({ msg: "未读取到Excel中的数据！" });
        return;
    }

    checkWireropeDetailModels.value = Gx.DeepCopy(oldCheckWireropeDetailModels);

    //需要的excel中的数据
    let _data = data[0].Sheet1;

    //是否为详情的数据
    let isDetail = true;

    //从excel中的第4行开始读数据
    for (let i = 3; i < _data.length; i++) {
        let row = _data[i];

        //如果遇到这个标识，则说明详情的数据已经读完，该读取详情明细的数据了
        if (row.A == "断丝直径详细检测数据") {
            isDetail = false;
            i++;
            continue;
        }

        if (isDetail == true) {
            //详情的数据，即上半部分的数据
            if (!Gx.IsEmpty(checkWireropeDetailModels.value[i - 3].name) && row.A != checkWireropeDetailModels.value[i - 3].name) {
                App.Tips({ msg: "Excel数据与当前检测数据不一致！" });
                checkWireropeDetailModels.value = Gx.DeepCopy(oldCheckWireropeDetailModels);
                return;
            }

            let temp = checkWireropeDetailModels.value[i - 3];
            temp.name = row.A;
            temp.dsCnt = row.B;
            temp.dsLa = row.C;
            temp.zjPosition = row.D;
            temp.zjDia = row.E;
            temp.jsjmPosition = row.F;
            temp.jsjmLma = row.G;
            temp.nianJu = row.H;
            temp.othFuShi = row.I;
            temp.othMoSun = row.J;
            temp.othQiTa = row.K;
            temp.othZongHe = row.L;
            checkWireropeDetailModels.value[i - 3] = temp;
        } else {
            //断丝、直径的录入数据
            let findIdx = checkWireropeDetailModels.value.findIndex((x) => x.name == row.A);
            if (findIdx == -1) {
                App.Tips({ msg: "Excel数据与当前检测数据不一致！" });
                checkWireropeDetailModels.value = Gx.DeepCopy(oldCheckWireropeDetailModels);
                return;
            }

            let findItem = Gx.DeepCopy(checkWireropeDetailModels.value[findIdx]);

            if (!Gx.IsEmpty(row.B) && !Gx.IsEmpty(row.C)) {
                findItem.checkWireropeDetailDataModels.push({
                    type: Enums.CheckWireropeDetailData_Type.断丝,
                    position: row.B,
                    num: row.C,
                    usingWireropeID: usingWireropeID.value,
                });
            }

            if (!Gx.IsEmpty(row.D) && !Gx.IsEmpty(row.E)) {
                findItem.checkWireropeDetailDataModels.push({
                    type: Enums.CheckWireropeDetailData_Type.直径,
                    position: row.D,
                    num: row.E,
                    usingWireropeID: usingWireropeID.value,
                });
            }

            checkWireropeDetailModels.value[findIdx] = findItem;
        }
    }

    //数据全部读取完后，把DetailDataModels中的数据按类型分开
    for (var i = 0; i < checkWireropeDetailModels.value.length; i++) {
        let item = checkWireropeDetailModels.value[i];
        item.dsList = item.checkWireropeDetailDataModels.filter((x) => x.type == Enums.DataEntry_Type.断丝);
        item.zjList = item.checkWireropeDetailDataModels.filter((x) => x.type == Enums.DataEntry_Type.直径);

        //断丝
        for (let j = 0; j < item.dsList.length; j++) {
            let jtem = item.dsList[j];

            if (Number(jtem.position) > Number(installLengthNum.value)) {
                App.Tips({ msg: `${item.name}断丝序号【${Number(i) + 1}】的位置信息必须小于安装长度${installLengthNum.value}米！` });
                checkWireropeDetailModels.value = Gx.DeepCopy(oldCheckWireropeDetailModels);
                return;
            }

            let nextJtem = item.dsList[Number(j) + 1];
            if (Number(j) + 1 < item.dsList.length) {
                if (Number(jtem.position) > Number(nextJtem.position)) {
                    App.Tips({ msg: `${item.name}序号【${Number(j) + 1}】的位置信息必须小于序号【${Number(j) + 2}】的位置信息！` });
                    checkWireropeDetailModels.value = Gx.DeepCopy(oldCheckWireropeDetailModels);
                    return;
                }
                // 判断当前位置+捻距是否超过下一位置
                if (Number(jtem.position) + Number(usingWireropeData.value.nianJu) / 100 >= Number(nextJtem.position)) {
                    jtem.sum = Number(jtem.num) + Number(nextJtem.num);
                    jtem.dsEnd = nextJtem.position;
                    jtem.dsStart = jtem.position;
                } else {
                    jtem.sum = Number(jtem.num);
                    jtem.dsStart = jtem.position;
                    jtem.dsEnd = jtem.position;
                }
            } else {
                jtem.sum = Number(jtem.num);
                jtem.dsStart = jtem.position;
                jtem.dsEnd = jtem.position;
            }

            let maxData = _.maxBy(item.dsList, (o: any) => {
                return o.sum;
            });
            let positionArr = _.filter(item.dsList, function (o: any) {
                return o.sum == maxData.sum;
            });

            onCloseDataEntry(item.dsList, positionArr, Gx.IsEmpty(maxData) ? 0 : maxData.sum, Enums.DataEntry_Type.断丝, i);
        }

        //直径
        for (let j = 0; j < item.zjList.length; j++) {
            let jtem = item.zjList[j];

            if (Number(jtem.position) > Number(installLengthNum.value)) {
                App.Tips({ msg: "直径序号【" + (Number(i) + 1) + "】的位置信息必须小于安装长度" + installLengthNum.value + "米！" });
                checkWireropeDetailModels.value = Gx.DeepCopy(oldCheckWireropeDetailModels);
                return;
            }

            let minData = _.minBy(item.zjList, (o: any) => {
                return o.num;
            });

            let zjDia = ((1 - minData.num / Number(usingWireropeData.value.diameter)) * 100).toFixed(2);
            onCloseDataEntry(item.zjList, minData.position, zjDia, Enums.DataEntry_Type.直径, i);
        }

        if (!Gx.IsEmpty(item.nianJu)) {
            let nianJu = usingWireropeData.value.nianJu;
            let nianJuChange = Math.abs(Gx.Chu(Gx.Jian(item.nianJu, nianJu), nianJu) * 100).toFixed(2);
            item.nianJuChange = nianJuChange;
        }
    }

    App.Tips({ msg: `导入成功`, type: TipsType.Success });
};
</script>

<style scoped lang="scss">
.titWarp {
    display: flex;
    align-items: center;
    padding-bottom: 12px;
    .rowTitle {
        min-width: 100px;
    }
}
.el-tabs {
    box-sizing: border-box;
}

.infoBox {
    width: 100%;
    display: flex;
    align-items: center;
    .el-icon {
        font-size: 20px;
        padding-left: 6px;
    }
}
</style>
